/* eslint-disable no-console */
/* eslint-disable react/prop-types */
import React, { useState, useEffect } from 'react';
import track from 'utils/track';
import { Message, Dialog, Button } from '@teamix/ui';
import Moment from 'moment';
import exceed from 'utils/apimap';
import { navigateOpen } from 'utils/router';
import './index.scss';
import intl from '../../locale';

const { organization } = window.FORCE;

const PremiumService = ({ premiumstatus }) => {
  const hasSettingsAuth =
    organization.user_role === 'ADMIN' ||
    organization.user_role === 'ORG_ADMIN' ||
    organization.user_role === 'ORG_OWNER';
  const [visible, setVisible] = useState(false);
  const getBilling = async () => {
    const getAdvance = exceed.fetch({
      api: 'organization.advance',
      params: { orgId: window.FORCE.organization.id },
    });

    // const getOrgplan = exceed.fetch({ api: 'organization.orgplan' });
    Promise.all([getAdvance])
      .then((value) => {
        // getOrgplan
        // dispatch.getOrgplan(value[1]);
        setVisible(value[0]);
        !value[0] && premiumstatus && premiumstatus();
      })
      .catch((err) => {
        console.error(err);
      });
  };
  const getLocalStorage = () => {
    const localValue = window.localStorage.getItem(`codeBilling-${window.config.orgId}`);
    const dataValue = Moment().format('YYYY/MM/DD');
    const billingVisible = localValue
      ? JSON.parse(localValue).filter((va) => va === dataValue)
      : [];
    return billingVisible;
  };

  useEffect(() => {
    const billingVisible = getLocalStorage();

    if (billingVisible && billingVisible.length === 0 && hasSettingsAuth) {
      // 延迟1s调用，降低阻塞
      setTimeout(() => {
        getBilling();
      }, 1000);
    } else {
      premiumstatus && premiumstatus();
    }
  }, []);
  const onVisibilityChange = () => {
    const billingVisible = getLocalStorage();
    if (
      document.visibilityState === 'visible' &&
      hasSettingsAuth &&
      billingVisible &&
      billingVisible.length === 0
    ) {
      getBilling();
    }
  };
  useEffect(() => {
    document.addEventListener('visibilitychange', onVisibilityChange);
    return () => {
      document.removeEventListener('visibilitychange', onVisibilityChange);
    };
  }, []);
  const advancedBuyUrl = async () => {
    // const version = tools.getCookie('version') === 'ga' ? 'pre-' : '';
    await track({
      action: 'upgrade_premium',
      page: 'Dialog-VIP-code security',
      type: '',
      control: '',
    });

    navigateOpen(
      `https://devops.aliyun.com/org-admin/${
        window.config && window.config.orgId
      }/profile?buy=true`,
    );

    const localValue = window.localStorage.getItem(`codeBilling-${window.config.orgId}`);
    const setValue = localValue ? JSON.parse(localValue) : [Moment().format('YYYY/MM/DD')];
    // eslint-disable-next-line no-unused-expressions
    localValue ? setValue.push(Moment().format('YYYY/MM/DD')) : null;
    window.localStorage.setItem(`codeBilling-${window.config.orgId}`, JSON.stringify(setValue));
    // setVisible(false);
    // premiumstatus && premiumstatus();
  };
  const handleEnter = async () => {
    await track({
      action: 'start_trial',
      page: 'Dialog-VIP-code security',
      type: '',
      control: '',
    });

    const value = await exceed.fetch({
      api: 'organization.buyOrgPlan',
      params: { orgId: window.FORCE.organization.id },
      data: { order_plan_type: 'trial' },
    });

    if (value) {
      Message.success({
        title: intl.get({
          id: 'code-assets.components.premiumService.TheOrderHasBeenActivated',
          defaultMessage: '订单开通成功',
        }),
        duration: 1000,
      });

      // setVisible(false);
      // premiumstatus && premiumstatus();
    }

    const localValue = window.localStorage.getItem(`codeBilling-${window.config.orgId}`);
    const setValue = localValue ? JSON.parse(localValue) : [Moment().format('YYYY/MM/DD')];
    // eslint-disable-next-line no-unused-expressions
    localValue ? setValue.push(Moment().format('YYYY/MM/DD')) : null;
    window.localStorage.setItem(`codeBilling-${window.config.orgId}`, JSON.stringify(setValue));
    setVisible(false);
    premiumstatus && premiumstatus();
  };
  const billingDesc = (
    <div>
      <span>
        {intl.get({
          id: 'code-assets.components.premiumService.TheBasicFunctionsOfYunxiao',
          defaultMessage:
            '云效基础功能全面开放、不限人数免费使用。为了给您提供更优质的服务，「企业代码安全」升级为高级版套餐专属能力，包括：',
        })}
      </span>
      <ul>
        <li style={{ listStyle: 'inside', color: '#1b9aee' }}>
          {intl.get({
            id: 'code-assets.components.premiumService.MemberBehaviorSecurity',
            defaultMessage: '成员行为安全',
          })}
        </li>
        <li style={{ listStyle: 'inside', color: '#1b9aee' }}>
          {intl.get({
            id: 'code-assets.components.premiumService.SecurityNotification',
            defaultMessage: '安全通知',
          })}
        </li>
      </ul>
      <span>
        {intl.get({
          id: 'code-assets.components.premiumService.AdvancedEditionExclusiveAbilityLast',
          defaultMessage:
            '高级版专属能力限时免费使用 90 天\n        ，试用到期后将会关闭高级版专属功能，为避免影响企业研发管理工作，请关注到期时间，或及时升级套餐。',
        })}
      </span>
      <span style={{ display: 'block' }}>
        {intl.get({
          id: 'code-assets.components.premiumService.DingtalkConsultingGroup',
          defaultMessage: '钉钉咨询群（35967367）',
        })}
      </span>
      <img
        style={{ width: 90, display: 'inline-block' }}
        src="https://img.alicdn.com/imgextra/i3/O1CN014h8LSE23tP7iecHLd_!!6000000007313-2-tps-430-440.png"
      />
    </div>
  );

  return (
    <Dialog
      className="pre-ser-dialog"
      title={false}
      onClose={() => {
        setVisible(false);
        premiumstatus && premiumstatus();
      }}
      visible={visible}
      footerAlign="right"
      shouldUpdatePosition
      footer={false}
      closeable={false}
      hasMask
    >
      <div className="pre-ser-content">
        <img
          className="pre-ser-sideImg"
          src="https://img.alicdn.com/imgextra/i3/O1CN0144b6t11Rs4Z3BTDss_!!6000000002166-2-tps-530-812.png"
          alt=""
        />

        <div className="pre-ser-main">
          <div className="pre-ser-title">
            {intl.get({
              id: 'code-assets.components.premiumService.ImportantReminder',
              defaultMessage: '重要提醒',
            })}
          </div>
          <div className="pre-ser-desc">{billingDesc}</div>
          <div className="pre-ser-btns">
            <Button type="primary" onClick={handleEnter} style={{ marginRight: 16 }}>
              {intl.get({
                id: 'code-assets.components.premiumService.EnterTheFreeTrial',
                defaultMessage: '立即进入免费试用至',
              })}
              {Moment().add(90, 'd').format('YYYY-MM-DD')}
            </Button>
            <Button onClick={advancedBuyUrl} type="primary">
              {intl.get({
                id: 'code-assets.components.premiumService.UpgradePlan',
                defaultMessage: '升级套餐',
              })}
            </Button>
          </div>
        </div>
      </div>
    </Dialog>
  );
};

export default PremiumService;
